package cn.hxzy.service.impl;

import cn.hxzy.common.R;
import cn.hxzy.entity.Orders;
import cn.hxzy.entity.Train;
import cn.hxzy.entity.User;
import cn.hxzy.mapper.OrdersMapper;
import cn.hxzy.mapper.TrainMapper;
import cn.hxzy.mapper.UserMapper;
import cn.hxzy.service.OrdersService;
import cn.hxzy.service.TrainService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private TrainMapper trainMapper;
    @Autowired
    private TrainService trainService;

    @Override
    @Transactional
    public R addOrder(Train train, String userName) {
        if (train.getSurplusSite()>0){
            train.setSurplusSite(train.getSurplusSite()-1);
            int i = trainMapper.updateById(train);
            if (i>0){
                redisTemplate.delete("trains");
                trainService.getTrain();
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("user_name",userName);
                User user = userMapper.selectOne(queryWrapper1);
                Orders orders = new Orders();
                orders.setUserId(user.getUserId());
                orders.setTrainId(train.getTrainId());
                orders.setMoney(train.getMoney());
                orders.setSeatNo((int)(train.getTotalSite()*Math.random()));
                int insert = ordersMapper.insert(orders);
                if(insert>0){
                    redisTemplate.opsForList().leftPush("myOrders"+userName,orders);
                    return R.ok().message("订票成功").code(1);
                }else {
                    return R.error().code(-1).message("订票失败");
                }
            }else {
                return R.error().code(-2).message("订票失败");
            }
        }else {
            return R.error().code(-3).message("订票失败");
        }
    }
}
